package com.wonders.frame.controller;

import com.gcr.server.response.Response;
import com.wonders.frame.aspect.LoginAspect;
import com.wonders.frame.common.Enum.LoginCodeEnum;
import com.wonders.frame.common.Enum.ResponseCodeEnum;
import com.wonders.frame.common.Enum.SessionKeyEnum;
import com.wonders.frame.common.util.RandomValidateCodeUtil;
import com.wonders.frame.common.util.ServerUtil;
import com.wonders.frame.controller.core.CoreController;
import com.wonders.frame.entity.AuthAccount;
import com.wonders.frame.entity.AuthPermission;
import com.wonders.frame.service.AuthAccountService;
import com.wonders.frame.service.Core.CoreCurdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping()
public class LoginController extends CoreController<AuthAccount> {
    @Autowired
    private AuthAccountService service;

    @RequestMapping("login")
    public Response login(String account, String password, String verify, HttpServletRequest request) {
        Response response;
        HttpSession session = request.getSession();
        //验证验证码是否正确
        String sessionVerify = (String) session.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);

        //验证码不正确
        if (!Objects.equals(sessionVerify, verify)) {
            return errorResponse(ResponseCodeEnum.VERIFY_MISMATCH, null);
        }

        //1.验证用户名密码
        //1.1.根据用户名获取用户
        AuthAccount acc = service.getAccbyAccount(account);

        //账号是否存在
        if (acc == null || StringUtils.isEmpty(acc.getAccount())) {
            return errorResponse(ResponseCodeEnum.ACCOUNT_NOT_EXIST, null);
            //response= getResponseWithoutData(LoginCodeEnum.ACCOUNT_NOT_EXIST.getCode(), LoginCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
        }

        //账号是否注销 0正常 1注销
        if (StringUtils.isEmpty(acc.getAccountStatus()) || acc.getAccountStatus() == 1) {
            return errorResponse(ResponseCodeEnum.ACCOUNT_LOGOUT, null);
        }

        //密码输入错误三次 已锁定
        if (StringUtils.isEmpty(acc.getErrorCount()) || acc.getErrorCount() >= 3) {
            return errorResponse(ResponseCodeEnum.PASSWORD_MISTAKETOOMANY, null);
        }
        //SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        Date sysDate = new Date();

        //密码是否已过期
        if (acc.getExpDate().getTime() < sysDate.getTime()) {
            return errorResponse(ResponseCodeEnum.PASSWORD_EXPIRED, null);
        }


        //1.2.验证登录信息
        switch (service.checkLogin(acc, account, password)) {
            //    2.返回用户所有权限信息
            //2.1.成功则获取对应权限
            case SUCCESS:
                //在当前登录时间的基础上延长一个月
                acc.setExpDate(getAfterMonth(1));
                service.extendExpDate(acc);
                Map<String, Object> map = new HashMap<String, Object>();
                List<AuthPermission> pers = service.getAllPermissionByRoles(new ArrayList<>(acc.getRoles()));
                //排序权限子节点
                pers = service.sortAuthPermission(pers);
                map.put("permissionList", pers);
                map.put("account", acc);
                response = getResponse(map, LoginCodeEnum.SUCCESS.getCode(),
                        LoginCodeEnum.SUCCESS.getMsg());
                //3.将登录的用户信息添加到session中
                //HttpSession session = request.getSession();
                session.setMaxInactiveInterval(3600);
                session.setAttribute(SessionKeyEnum.USERINFO.name(), acc);
                List<AuthPermission> ps = service.getApiPermission(new ArrayList<>(acc.getRoles()));
                //将按钮级权限列表添加到session中，方便获取
                session.setAttribute(SessionKeyEnum.API_PERMISSION.name(), ps);
                String ip = ServerUtil.getIpAddr(request);
/*
      /*
                单点登录：
                1.判断账号是否登录过
                  1.1.登陆过则判断sessionId和当前登录的账号对应的sessionId一致
                    1.1.1.一致则更新SESSION_MAP中该账号对应的session
                    1.1.2.不一致则移除SESSION_MAP中对应账号的session记录，
                          并添加新的账号->session对应关系
                  1.2.未登录过则在ACCOUNT_IP、SESSION_MAP添加相应的对应关系
                 */

                if(LoginAspect.ACCOUNT_SESSION.containsKey(account)){
                    if(!Objects.equals(session.getId(),
                            LoginAspect.ACCOUNT_SESSION.get(account)) ){
                        LoginAspect.ACCOUNT_SESSION.put(account, session.getId());
                    }
                }else{
                    LoginAspect.ACCOUNT_SESSION.put(account, session.getId());
                }

                break;
            case ACCOUNT_NOT_EXIST:
                response = getResponseWithoutData(LoginCodeEnum.ACCOUNT_NOT_EXIST.getCode(), LoginCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
                break;
            case PASSWORD_IS_WRONG:
                response = getResponseWithoutData(LoginCodeEnum.PASSWORD_IS_WRONG.getCode(), LoginCodeEnum.PASSWORD_IS_WRONG.getMsg());
                break;
            default:
                response = new Response();
        }
        return response;
    }

    @Override
    protected CoreCurdService getService() {
        return service;
    }

    private  Date getAfterMonth(int number) {
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        Date date = new Date();
        c.setTime(date);//设置日历时间
        c.add(Calendar.MONTH,number);//在日历的月份上增加6个月
        return  c.getTime();
    }

    //登出
    @RequestMapping("loginOut")
    public Response loginOut() {
        return null;
    }
}
